package net.omnivention.proxy;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.Logger;

public class HttpHeaders {
	private static Logger logger = Logger.getLogger(HttpHeaders.class);

	private Map<String, String> cookies;

	private ArrayList<String> lines;

	public HttpHeaders() {
		lines = new ArrayList<String>();
		cookies = new HashMap<String, String>();
	}

	public void add(String line) {
		line = line.trim();
		logger.debug(line);
		if (line.equals("")) {
			return;
		}
		lines.add(line);
	}

	public String getHeaderValue(String headerName) {
		for (String line : lines) {
			if (line.indexOf(headerName) > -1) {
				int c = line.indexOf(":");
				return line.substring(c + 1, line.length()).trim();
			}
		}

		return null;
	}

	public void setHeaderValue(String headerName, String value) {
		for (int i = 0; i < lines.size(); i++) {
			String line = lines.get(i);
			if (line.indexOf(headerName) > -1) {
				line = headerName + ": " + value;
				lines.set(i, line.trim());
				return;
			}
		}
	}

	public byte[] getAsByteArray() {
		return toString().getBytes();
	}

	public String toString() {
		StringBuffer s = new StringBuffer();

		for (int i = 0; i < lines.size() - 1; i++) {
			String line = lines.get(i);
			s.append(line + HttpUtility.NEWLINE);
		}
		s.append(lines.get(lines.size() - 1));
		return s.toString();
	}
}
